import React, {useEffect, useState} from 'react';

import './index.less';
import {Button, Card, Form, Input, message, Modal, Select, Table} from 'antd';
import LinkButton from '../../components/LinkButton';
import {formateDate} from '../../utils/dateUtils'
import {reqAddUser, reqDeleteUser, reqUpdateUser, reqUserList} from '../../api'

/**
 * 二级路由 用户管理
 */
function User(){
  /* 用户列表 */
  const [userList,setUserList] = useState([]);
  /* 用户 */
  const [user,setUser] = useState({});
  /* 角色列表 */
  const [roleList,setRoleList] = useState([]);
  //是否展示新增和修改页面 0=关闭 1=新增/修改
  const [showStatus,setShowStatus] = useState(0);

  /**
   * 获取用户列表
   */
  async function reqGetUserList(){
    //调用获取分类列表的方法
    const response = await reqUserList();
    //判断获取数据是否成功
    if(response.status === 0){
      //成功后添加到state中
      setUserList(response.data.users);
      setRoleList(response.data.roles);
    }else{
      // 获取数据失败！
      message.error("获取数据失败！");
    }
  }

  useEffect(function () {
    reqGetUserList().then();
  },[]);

  /**
   * 显示修改用户界面
   */
  function showUpdate(user) {
    setUser(user);
    setShowStatus(2)
  }

  /**
   * 显示新增用户界面
   */
  function showAdd() {
    setShowStatus(1);
  }

  /**
   * 删除用户
   */
  function deleteUser(user) {
    Modal.confirm({
      title: `确认删除${user.username}吗?`,
      onOk: async () => {
        const result = await reqDeleteUser(user._id)
        if(result.status===0) {
          message.success('删除用户成功!')
          reqGetUserList().then();
        }
      }
    })
  }

  /**
   * 新增或者修改页面，取消点击事件
   */
  function handleCancel(){
    //点击取消关闭页面
    setShowStatus(0);
  }

  /**
   * 新增用户
   * @param values 表单所有数据
   */
  async function onFinishAdd(values) {
    // 提交添加的请求
    const result = await reqAddUser(values);
    // 3. 更新列表显示
    if (result.status === 0) {
      message.success("添加用户成功");
      reqGetUserList().then();
    }
    setShowStatus(0);
  }

  /**
   * 修改用户
   * @param values 表单所有数据
   */
  async function onFinishUpdate(values) {
    values._id = user._id;
    // 提交添加的请求
    const result = await reqUpdateUser(values);
    // 3. 更新列表显示
    if (result.status === 0) {
      message.success("修改用户成功");
      reqGetUserList().then();
    }
    setShowStatus(0);
  }

  //卡片左侧
  const title = (
    <span>
      <Button type="primary" onClick={showAdd}>
        新增用户
      </Button>
    </span>
  );

  //表格标题
  const columns = [
    {
      title: '用户名',
      dataIndex: 'username'
    },
    {
      title: '邮箱',
      dataIndex: 'email'
    },
    {
      title: '电话',
      dataIndex: 'phone'
    },
    {
      title: '注册时间',
      dataIndex: 'create_time',
      render: formateDate
    },
    {
      title: '所属角色',
      dataIndex: 'role_id',
      render: (role_id) => roleList.find((role) => role_id === role._id).name
    },
    {
      title: '操作',
      render: (user) => (
        <span>
      <LinkButton onClick={() => showUpdate(user)}>修改</LinkButton>
      <LinkButton onClick={() => deleteUser(user)}>删除</LinkButton>
    </span>
      )
    },
  ];

  return (
    <div>
      <Card
        title={title}
      >
        <Table
          rowKey="_id"
          bordered
          dataSource={userList}
          columns={columns}
          pagination={{defaultPageSize: 5}}
        />
      </Card>
      <Modal footer={null} destroyOnClose title="新增用户" open={showStatus === 1} onCancel={handleCancel}>
        <Form
          name="add-form"
          className="add-form"
          onFinish={onFinishAdd}
          //根据name展示默认值
          initialValues={{
          }}
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[
              {required: true, message: "用户名不能为空!" },
            ]}
          >
            <Input placeholder='请输入用户名'/>
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[
              {required: true, message: "密码不能为空!" },
            ]}
          >
            <Input type='password' placeholder='请输入密码'/>
          </Form.Item>
          <Form.Item
            label="手机号"
            name="phone"
            rules={[
              {required: true, message: "手机号不能为空!" },
            ]}
          >
            <Input placeholder='请输入手机号'/>
          </Form.Item>
          <Form.Item
            label="邮箱"
            name="email"
            rules={[
              {required: true, message: "邮箱不能为空!" },
            ]}
          >
            <Input placeholder='请输入邮箱'/>
          </Form.Item>
          <Form.Item
            label="角色"
            name="role_id"
            rules={[
              {required: true, message: "角色不能为空!" },
            ]}
          >
            <Select>
              {
                roleList.map(role => <Select.Option key={role._id} value={role._id}>{role.name}</Select.Option>)
              }
            </Select>
          </Form.Item>
          <Form.Item style={{textAlign: 'right'}}>
            <Button onClick={handleCancel} style={{marginRight: 10}}>
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              确定添加
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      <Modal footer={null} destroyOnClose title="修改用户" open={showStatus === 2} onCancel={handleCancel}>
        <Form
          name="update-form"
          className="update-form"
          onFinish={onFinishUpdate}
          //根据name展示默认值
          initialValues={{
            username: user.username,
            password: user.password,
            phone: user.phone,
            email: user.email,
            role_id: user.role_id,
          }}
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[
              {required: true, message: "用户名不能为空!" },
            ]}
          >
            <Input placeholder='请输入用户名'/>
          </Form.Item>
          <Form.Item
            label="手机号"
            name="phone"
            rules={[
              {required: true, message: "手机号不能为空!" },
            ]}
          >
            <Input placeholder='请输入手机号'/>
          </Form.Item>
          <Form.Item
            label="邮箱"
            name="email"
            rules={[
              {required: true, message: "邮箱不能为空!" },
            ]}
          >
            <Input placeholder='请输入邮箱'/>
          </Form.Item>
          <Form.Item
            label="角色"
            name="role_id"
          >
            <Select>
              {
                roleList.map(role => <Select.Option key={role._id} value={role._id}>{role.name}</Select.Option>)
              }
            </Select>
          </Form.Item>
          <Form.Item style={{textAlign: 'right'}}>
            <Button onClick={handleCancel} style={{marginRight: 10}}>
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              确定添加
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

export default User;